import { request } from 'bee/utils/request';

const types = {
  REQUEST_INDEX_DATA: 'REQUEST_INDEX_DATA',
  RECEIVE_INDEX_DATA: 'RECEIVE_INDEX_DATA',
  REQUEST_ERROR: 'REQUEST_ERROR',
};

export const actions = {
  requestData: async (dispatch, user) => {
    dispatch({ type: types.REQUEST_INDEX_DATA });

    const data = await request('/index');
    if (data.status === 0) {
      dispatch({ type: types.RECEIVE_INDEX_DATA, data: data.body });
    }
    dispatch({ type: types.REQUEST_ERROR, err: data });
  },
  receiveData: () => ({
    type: types.RECEIVE_INDEX_DATA,
  }),
  requestError: () => ({
    type: types.requestError,
  }),
};

const initialState = {
  isFetching: false,
  isError: false,
  carousels: [],
  navs: [],
  allList: [],
  moneyList: [],
  healthList: [],
  acciList: [],
  life: [],
};

export const reducers = (state = initialState, action) => {
  switch (action.type) {
    case types.REQUEST_INDEX_DATA:
      return { ...state, isFetching: true };
    case types.RECEIVE_INDEX_DATA:
      return { ...state, ...action.data };
    case types.requestError:
      return { ...state, isError: action.err, isFetching: false };
    default:
      return state;
  }
};
